package data;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.Activity;

public class GetAccountList extends DBTask<Void, Void, List<Account>> {

	/**
	 * Constructs task to get a list of accounts
	 * 
	 * @param activity
	 *            the current Android activity
	 * @throws DBInterfaceError
	 */
	public GetAccountList(Activity activity) throws DBInterfaceError {
		super(activity);
	}

	/**
	 * gets the list of accounts from a database
	 * 
	 * @return list of Items
	 * @throws DBInterfaceError
	 */
	@Override
	public List<Account> getResult() throws DBInterfaceError {
		execute();
		List<Account> accounts = null;
		try {
			accounts = get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		return accounts;
	}

	/**
	 * Searches for and returns a list of accounts from a database
	 * 
	 * @return list of Items from database
	 */
	@Override
	protected List<Account> doInBackground(Void... arg0) {
		PreparedStatement getItemsQuery;
		List<Account> list = null;
		try {
			getItemsQuery = conn
					.prepareStatement("SELECT * FROM account ORDER BY accountName");
			ResultSet set = getItemsQuery.executeQuery();
			list = new ArrayList<Account>();
			while (set.next()) {
				Account account = new Account();
				account.setAccountName(set.getString("accountName"));
				account.setEmail(set.getString("email"));
				account.setPassword(set.getString("password"));
				account.setRealName(set.getString("realName"));
				account.setPhoneNumber(set.getString("phoneNumber"));
				account.setLoginTimes(set.getInt("loginTimes"));
				account.setIsLocked(set.getBoolean("locked"));
				account.setIsAdmin(set.getBoolean("isAdmin"));

				list.add(account);
			}

		} catch (Exception e) {
			System.err.println(e);
		}

		return list;
	}

}
